package com.example.waterdispenserm2.mo.water;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Toast;

import com.example.waterdispenserm2.app.LPHYApplication;
import com.example.waterdispenserm2.base.BasicsActivity;
import com.example.waterdispenserm2.databinding.ActivityWaterDispenserBinding;
import com.example.waterdispenserm2.mo.copy.CopyInductionCookerSlave;
import com.example.waterdispenserm2.mo.copy.CopySerialActivity;
import com.example.waterdispenserm2.mo.inductioncong.SerialCookerDisplayActivity;
import com.example.waterdispenserm2.mo.inductionmain.InductionCookerActivity;
import com.example.waterdispenserm2.mo.ttl.d.CookerSlaveActivity;
import com.example.waterdispenserm2.mo.ttldeep.DeepSeekActivity;
import com.example.waterdispenserm2.mo.water.SerialPortHelper;
import com.example.waterdispenserm2.mo.usbcong.UsbCongInductionCookerDisplayActivity;
import com.example.waterdispenserm2.mo.usbmain.UsbMainInductionCookerActivity;
import com.example.waterdispenserm2.util.SPUtils;

import java.util.Timer;
import java.util.TimerTask;

public class WaterDispenserActivity extends BasicsActivity<ActivityWaterDispenserBinding> {

    private SerialPortHelper serialPort;
    private Handler handler = new Handler();

    // 状态变量
    private int currentVolume = 0;     // 当前水量 (ml)
    private int currentFlowRate = 0;   // 当前流速 (ml/min)
    private float currentTemp = 0;     // 当前温度 (°C)
    private int setVolume = 500;         // 设置水量 (ml)
    private int setTemp = 25;          // 设置温度 (°C)
    private int setFlowRate = 500;     // 设置流速 (ml/min)

    // 定时器
    private Timer volumeUpdateTimer;
    private Timer heartbeatTimer;
    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initView() {
        if (!TextUtils.isEmpty(SPUtils.getSerialPortNum())){
            open();
        }

        if (!TextUtils.isEmpty(binding.etAdd.getText().toString().trim())) {
            // 绑定服务
            binding.btOpen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!LPHYApplication.bound) {
                        if ("0".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS0");
                        } else if ("1".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS1");
                        } else if ("2".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS2");
                        } else if ("3".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS3");
                        } else if ("4".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS4");
                        } else if ("5".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS5");
                        } else if ("6".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS6");
                        } else if ("7".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS7");
                        }


                        open();

                    }else {
                        Toast.makeText(WaterDispenserActivity.this,"设备已连接状态",Toast.LENGTH_LONG).show();
                    }
                }
            });
        }


        binding.btClase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDestroy();
            }
        });

        // 设置滑块监听
        setupSliders();

        // 设置按钮点击事件
        binding.btnStart.setOnClickListener(v -> startDispensing());
        binding.btnStop.setOnClickListener(v -> stopDispensing());
        binding.btnQuery.setOnClickListener(v -> queryStatus());

        binding.btnSerial1.setOnClickListener(v->startActivity(new Intent(this, InductionCookerActivity.class)));
        binding.btnSerial2.setOnClickListener(v->startActivity(new Intent(this, SerialCookerDisplayActivity.class)));//开始生成
        binding.btnTTL1.setOnClickListener(v->startActivity(new Intent(this, CookerSlaveActivity.class)));//dou生成
        binding.btnTTL2.setOnClickListener(v->startActivity(new Intent(this, DeepSeekActivity.class)));//de生成
        binding.btnUSB2.setOnClickListener(v->startActivity(new Intent(this, UsbCongInductionCookerDisplayActivity.class)));
        binding.btnCopy1.setOnClickListener(v->startActivity(new Intent(this, CopySerialActivity.class)));//电平一起生成
        binding.btnCopy2.setOnClickListener(v->startActivity(new Intent(this, Hob2DisplayBoardActivity.class)));//电平一起生成
    }

    @Override
    protected ActivityWaterDispenserBinding getViewBinding() {
        return ActivityWaterDispenserBinding.inflate(LayoutInflater.from(this));
    }
    boolean isOpen;
    private void open(){
        // 初始化串口
        serialPort = new SerialPortHelper(data -> {
            // 处理接收到的数据
            handleReceivedData(data);
        });

        // 打开串口 (根据实际设备修改路径和波特率)
        isOpen=serialPort.open(SPUtils.getSerialPortNum(), 9600);

        if (isOpen) {
            binding.tvStatus.setText("状态: 已连接");
        }else {
            Toast.makeText(WaterDispenserActivity.this, "串口打开失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void setupSliders() {
        binding.sbTemp.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                setTemp = progress;
                binding.etTargetTemp.setText(String.valueOf(progress));
            }
            @Override public void onStartTrackingTouch(SeekBar seekBar) {}
            @Override public void onStopTrackingTouch(SeekBar seekBar) {}
        });

        binding.sbFlow.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                setFlowRate=progress;
                binding.etFlowRate.setText(String.valueOf(setFlowRate));
            }
            @Override public void onStartTrackingTouch(SeekBar seekBar) {}
            @Override public void onStopTrackingTouch(SeekBar seekBar) {}
        });

        binding.sbVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                setVolume=progress;
                binding.etVolume.setText(String.valueOf(setVolume));
            }
            @Override public void onStartTrackingTouch(SeekBar seekBar) {}
            @Override public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }

    private void startDispensing() {
        try {
            setTemp = Integer.parseInt(binding.etTargetTemp.getText().toString());
            setFlowRate = Integer.parseInt(binding.etFlowRate.getText().toString());
            setVolume = Integer.parseInt(binding.etVolume.getText().toString());

            // 重置当前状态
            currentVolume = 0;
            currentFlowRate = 0;
            currentTemp = 0;

            // 发送出水指令
            byte[] command = WaterDispenserProtocol.buildDispenseCommand(
                    setTemp, setFlowRate, setVolume, false);
            if (isOpen) {
                serialPort.sendData(command);


                // 启动心跳和水量更新
                startHeartbeat();
                startVolumeUpdate();

                // 更新UI
                updateTempUI();
                updateFlowRateUI();
                updateVolumeUI();
                Toast.makeText(this, "开始出水", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(this, "串口未连接", Toast.LENGTH_SHORT).show();
            }

        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的参数", Toast.LENGTH_SHORT).show();
        }
    }


    private void stopDispensing() {
        // 发送停止指令: A2 00
        byte[] command = WaterDispenserProtocol.buildCommandFrame((byte) 0xA2, new byte[]{0x00});
        if (isOpen) {
            serialPort.sendData(command);
            // 停止定时器
            stopHeartbeat();
            stopVolumeUpdate();

            Toast.makeText(this, "已停止出水", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(this, "串口未打开", Toast.LENGTH_SHORT).show();
        }


    }

    private void queryStatus() {
        // 发送查询指令: A3 00
        byte[] command = WaterDispenserProtocol.buildQueryCommand(0x00);
        if (isOpen) {
            serialPort.sendData(command);
            Toast.makeText(this, "查询状态中...", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(this, "串口未打开", Toast.LENGTH_SHORT).show();
        }
    }

    private void startHeartbeat() {
        stopHeartbeat();
        heartbeatTimer = new Timer();
        heartbeatTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                // 发送心跳 (0x0A)
                serialPort.sendData(new byte[]{0x0A});
            }
        }, 0, 1000); // 每秒发送一次心跳
    }

    private void stopHeartbeat() {
        if (heartbeatTimer != null) {
            heartbeatTimer.cancel();
            heartbeatTimer = null;
        }
    }

    private void startVolumeUpdate() {
        stopVolumeUpdate();
        volumeUpdateTimer = new Timer();
        volumeUpdateTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                // 查询累计水量
                byte[] volumeQuery = WaterDispenserProtocol.buildWaterVolumeQuery();
                serialPort.sendData(volumeQuery);

                // 查询瞬时流速
                byte[] flowQuery = WaterDispenserProtocol.buildFlowRateQuery();
                serialPort.sendData(flowQuery);
            }
        }, 0, 1000); // 每秒查询一次
    }

    private void stopVolumeUpdate() {
        if (volumeUpdateTimer != null) {
            volumeUpdateTimer.cancel();
            volumeUpdateTimer = null;
        }
    }

    private void handleReceivedData(byte[] data) {
        // 1. 尝试解析状态数据 (B8指令)
        WaterDispenserProtocol.DispenserStatus status =
                WaterDispenserProtocol.parseStatusData(data);
        if (status != null) {
            runOnUiThread(() -> updateStatusUI(status));
            return;
        }

        // 2. 尝试解析累计水量数据 (B5指令)
        int volume = WaterDispenserProtocol.parseWaterVolumeData(data);
        if (volume >= 0) {
            currentVolume = volume;
            runOnUiThread(() -> updateVolumeUI());
            return;
        }

        // 3. 尝试解析瞬时流速数据 (B4指令)
        int flowRate = WaterDispenserProtocol.parseFlowRateData(data);
        if (flowRate >= 0) {
            currentFlowRate = flowRate * 10; // 协议中流速缩小了10倍
            runOnUiThread(() -> updateFlowRateUI());
            return;
        }

        // 4. 尝试解析温度数据 (B3指令)
        float temperature = WaterDispenserProtocol.parseTemperatureData(data);
        if (temperature != -1000) { // 使用特殊值表示无效温度
            currentTemp = temperature;
            runOnUiThread(() -> updateTempUI());
        }
    }

    private void updateStatusUI(WaterDispenserProtocol.DispenserStatus status) {
        // 更新温度
        currentTemp = status.temperature;
        updateTempUI();

        // 更新状态文本
        switch (status.mode) {
            case 0x01:
                binding.tvStatus.setText("状态: 待机");
                binding.layout.setBackgroundColor(Color.parseColor("#E0F7FA")); // 浅蓝色
                break;
            case 0x02:
                binding. tvStatus.setText("状态: 出水中");
                binding.layout.setBackgroundColor(Color.parseColor("#C8E6C9")); // 浅绿色
                break;
        }

        // 更新水源状态
        if (status.waterStatus == 0x01 || status.flowStatus == 0x01) {
            binding.tvStatus.append(" | 有水");
        } else {
            binding.tvStatus.append(" | 缺水");
            binding.layout.setBackgroundColor(Color.parseColor("#FFCDD2")); // 浅红色
        }

        // 如果出水完成，停止定时器
        if (status.mode == 0x01) {
            stopVolumeUpdate();
        }
    }

    private void updateTempUI() {
        binding.tvCurrentTemp.setText(String.format("温度: %.1f°C", currentTemp));

        // 更新温度进度条
//        if (setTemp > 0) {
//            int progress = (int) (currentTemp / setTemp * 100);
//            if (progress > 100) progress = 100;
//            binding.progressTemp.setProgress(progress);
//        }
    }

    private void updateFlowRateUI() {
        binding.tvCurrentTemp.setText(String.format("流速: %d ml/min", currentFlowRate));

        // 更新流速进度条
//        if (setFlowRate > 0) {
//            int progress = (int) ((float) currentFlowRate / setFlowRate * 100);
//            if (progress > 100) progress = 100;
//            binding.progressFlow.setProgress(progress);
//        }
    }

    private void updateVolumeUI() {
        binding.tvCurrentVolume.setText(String.format("水量: %d/%d ml", currentVolume, setVolume));

        // 更新水量进度条
//        if (setVolume > 0) {
//            int progress = (int) ((float) currentVolume / setVolume * 100);
//            if (progress > 100) progress = 100;
//            binding.progressVolume.setProgress(progress);
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清理资源
        stopHeartbeat();
        stopVolumeUpdate();
        if (serialPort != null) {
            serialPort.close();
        }
    }
}